package com.ce.framework.context;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ce.framework.exception.AppException;
import com.ce.util.RegeditUtil;

public class FrameworkContext {

	static ServletContext context;
	
	static ApplicationContext appContext;
	//系统路径
	static String appPath;
	
	public static String path;
	
	static String systemTitle;
	
	public static String getSystemTitle(){
		if(systemTitle!=null)
			return systemTitle;
		systemTitle = RegeditUtil.getRegeditStringValue("SYSTEM_SEG_NAME");
		return systemTitle;
	}

	/**
	 * 根据BEAN的ID，从SPRING中得到注册的BEAN对象。
	 * @param beanId 在SPRING配置文件中注册的BEANID。
	 * @return
	 */
	public static Object getBean(String beanId)
		throws AppException{
		if(appContext==null){
			appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		}
		return appContext.getBean(beanId);
	}
	
	public static Connection getConnection() throws SQLException{
		Connection con = null;
		try {
			DataSource ds = (DataSource)getBean("dataSource");
			con = ds.getConnection();
		} catch (AppException e) {
			Logger.getLogger(FrameworkContext.class).error("在Spring窗口中找不到id为dataSource的Bean，可能是程序未正常启动", e);
		}
		return con;
	}
	public static String getAppPath() {
		return appPath;
	}

	public static void setAppPath(String path) {
		appPath = path;
	}
	
	public static String getPath(){
		if(path==null){
			HttpServletRequest request = ServletActionContext.getRequest();
			if(request==null){
				path = "";
			}
			path = request.getContextPath();
			if("/".equals(path)){
				path = "";
			}
		}
		return path;
	}
	
	public static void setAppContext(ApplicationContext appContext){
		FrameworkContext.appContext = appContext;
	}
	
}
